<?php

namespace App\Http\Controllers\Api\V1;

use App\Supports\Sms\Sms;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Requests\SmsCodeRequest;

class SmsController extends Controller
{
	public function code(): JsonResponse
    {
    	$lock = Cache::lock('send_sms_code', 15);

	    try {

		    if (! $lock->get()) fail('请稍后重试');

		    $request = app(SmsCodeRequest::class);

		    //$captchaData = Cache::get($request->captcha_key);

		    
	    	$type = $request->type;
	    	$phone = request('phone');

		    $sent = app(Sms::class)->phone($phone)
			    ->template(config("site.sms.code.template.{$type}"))
			    ->data('code', sms_code())->send();
			
		    $result = ['key' => $sent->first(), 'expired_at' => $sent->last()];
 
		   // Cache::forget($request->captcha_key);

            return response()->json($result, 201);

	    } finally {
	    	$lock->release();
	    }
    }
}
